<template>
  <div class="singer" ref="singer">
   <list-view :data="singers" @select="selectSinger" ref="listview"/>
   <router-view></router-view>
  </div>
</template>

<script>
import ListView from './ListView'
import { getSingerList } from '../../network/singer'
import { ERR_OK } from '../../network/config'
import Singer from '../../assets/js/singer'
import { mapMutations } from 'vuex'
import { playlistMixin } from '../../assets/js/mixin'

const HOT_SINGER_LEN = 10
const HOT_NAME = '热门'

export default {
  mixins: [playlistMixin],
  data () {
    return {
      singers: []
    }
  },
  created () {
    this._getSingerList()
  },
  methods: {
    handlePlaylist (playlist) {
      const bottom = playlist.length ? '60px' : ''
      this.$refs.singer.bottom = bottom
      // this.$refs.listview.refresh()
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    }),
    //  获取歌手列表
    _getSingerList () {
      getSingerList().then(res => {
        if (res.code === ERR_OK) {
          this.singers = this._normalizeSinger(res.data.list)
        }
      })
    },
    // 聚合歌手列表
    _normalizeSinger (list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(
            new Singer({
              id: item.Fsinger_id,
              name: item.Fsinger_name,
              mid: item.Fsinger_mid
            })
          )
        }
        const key = item.Findex
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(
          new Singer({
            id: item.Fsinger_id,
            name: item.Fsinger_name,
            mid: item.Fsinger_mid
          })
        )
      })
      // 为了得到有序列表，我们需要处理 map
      let ret = [] // A~Z
      let hot = [] // 热门
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      // 字母排序
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(ret)
    },
    selectSinger (item) {
      this.$router.push({
        path: `/singer/${item.id}`
      })
      this.setSinger(item)
    }
  },
  components: {
    ListView
  }
}
</script>

<style lang="stylus" scoped>
.singer {
  position: fixed
  top: 88px
  bottom: 0
  width: 100%
}
</style>
